package com.qf.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.qf.blog.commons.constants.SysConsts;
import com.qf.blog.commons.utils.CookieUtils;
import com.qf.blog.commons.utils.UUIDUtils;
import com.qf.blog.entity.User;
import com.qf.blog.vo.UserToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

// token我们要入Redis
@Service
@Slf4j
public class UserTokenService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public UserToken createUserToken(User user) {

        // 1.封装userToken对象
        UserToken userToken = new UserToken();
        userToken.setUsername(user.getUsername());
        userToken.setUserId(user.getId());
        userToken.setHeaderUrl((user.getHeaderUrl()));
        userToken.setCreateTime(new Date()); // 登录时间
        userToken.setUuid(UUIDUtils.getId());

        // 2.准备key/value
        String key = String.format(SysConsts.RedisKeys.USER_LOGIN_TOKEN_KEY, userToken.getUuid());
        String value = JSON.toJSONString(userToken); // 把userToken对象转成JSON字符串就是一个字符串

        // 3.把userToken保存到redis中，过期时间为30M
        stringRedisTemplate.opsForValue()
                .set(key, value, SysConsts.TOKEN_VALID_TIME, TimeUnit.MINUTES);
        // 4.返回userToken
        return userToken;
    }

    // 根据uuid从redis查询userToken
    public UserToken getUserToken(String uuid) {
        String key = String.format(SysConsts.RedisKeys.USER_LOGIN_TOKEN_KEY, uuid);
        String json = stringRedisTemplate.opsForValue().get(key);
        if (!ObjectUtils.isEmpty(json)) {
            return JSON.parseObject(json, UserToken.class);
        }
        return null;
    }

    public Boolean remove() {
        String uuid = CookieUtils.getValue(SysConsts.LOGIN_COOKIE_KEY);
        String tokenKey = String.format(SysConsts.RedisKeys.USER_LOGIN_TOKEN_KEY, uuid);
        log.info("用户退出登录:" + tokenKey);
        stringRedisTemplate.delete(tokenKey);
        return true;
    }
}
